package com.xiyuan.smartutils.streams;

import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;

/**
 * 摘要输入流，写出流的同时，更新摘要信息
 *
 * @version v1.0.0 @author lgz 2017-4-11 新建与整理
 */
public class DigestInputStream extends FilterInputStream {
    private MessageDigest digest;
    private long length;
    
    public DigestInputStream(InputStream stream, MessageDigest digest) {
        super(stream);
        this.digest = digest;
    }
    
    /**************************************************************************/
    //读出流，同时更新摘要和数目
    
    /**************************************************************************/
    
    public int read() throws IOException {
        int ch = in.read();
        if (ch != -1) {
            digest.update((byte) ch);
            length++;
        }
        
        return ch;
    }
    
    public int read(byte[] b) throws IOException {
        int result = in.read(b);
        if (result != -1) {
            digest.update(b, 0, result);
            length += result;
        }
        return result;
    }
    
    public int read(byte[] b, int off, int len) throws IOException {
        int result = in.read(b, off, len);
        if (result != -1) {
            digest.update(b, off, result);
            length += len;
        }
        return result;
    }
    
    /**************************************************************************/
    //获取最终摘要和数目
    
    /**************************************************************************/
    
    public MessageDigest getMessageDigest() {
        return digest;
    }
    
    public byte[] digest() {
        return digest.digest();
    }
    
    public long length() {
        return length;
    }
    
    public String toString() {
        return "[DigestInputStream] " + digest.toString();
    }
}
